const WebSocket = require('ws')
const http = require('http')

const server = http.createServer()
const wss = new WebSocket.Server({ server })

/**
 * on ->  message
 *  {event:'', data:''}
 */

wss.on('connection', ws => {
  console.log('WebSocket 连接已建立')

  let msg = ''
  let event = ''

  ws.on('message', message => {
    if (typeof message === 'object') {
      msg = JSON.parse(message)
      event = msg.event
    } else {
      msg = message
    }

    if (event === 'reservation') {
      // 定义并发送广播事件1
      wss.clients.forEach(client => {
        if (client.readyState === WebSocket.OPEN) {
          client.send(
            JSON.stringify({
              type: 'reservation',
              data: '这是考试预约广播事件的消息'
            })
          )
        }
      })
    }

    if (event === 'exam') {
      // 定义并发送广播事件2
      wss.clients.forEach(client => {
        if (client.readyState === WebSocket.OPEN) {
          client.send(
            JSON.stringify({
              type: 'exam',
              data: '准备考试 预约时间到'
            })
          )
        }
      })
    }
  })
})

const PORT = process.env.PORT || 8866
server.listen(PORT, () => {
  console.log(`WebSocket 服务器运行在端口 ${PORT}`)
})
